package com.jzsk.variable.center.service.login;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jzsk.variable.center.common.base.ServiceException;
import com.jzsk.variable.center.common.utils.UUIDUtils;
import com.jzsk.variable.center.common.utils.redis.JedisUtil;
import com.jzsk.variable.center.dao.zhengxin.entity.SysUser;
import com.jzsk.variable.center.dao.zhengxin.mapper.SysUserMapper;
import com.jzsk.variable.center.domain.dto.login.LoginReqDTO;
import com.jzsk.variable.center.domain.dto.login.LoginRespDTO;
import com.jzsk.variable.center.domain.enums.StatusCodeEnum;
import com.jzsk.variable.center.domain.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    SysUserMapper sysUserMapper;

    @Resource
    JedisUtil jedisUtil;

    @Override
    public ResponseVO<LoginRespDTO> login(LoginReqDTO loginReqDTO) {
        String password = loginReqDTO.getPassword();
        boolean hasUpperCase = !password.equals(password.toLowerCase());
        boolean hasLowerCase = !password.equals(password.toUpperCase());
        if (!(hasUpperCase && hasLowerCase)) {
            throw new ServiceException(StatusCodeEnum.密码必须同时包含英文大小写字符);
        }

        SysUser sysUser = sysUserMapper.selectOne(Wrappers.lambdaQuery(new SysUser())
                .eq(SysUser::getLoginName, loginReqDTO.getLoginName()));
        if (sysUser == null) {
            throw new ServiceException(StatusCodeEnum.账号不存在);
        }
        if (!sysUser.getPassword().equalsIgnoreCase(SecureUtil.md5(loginReqDTO.getPassword()))) {
            throw new ServiceException(StatusCodeEnum.密码错误);
        }
        String sessionId = UUIDUtils.upperUuid();
        //有效期1小时，1小时后需要重新登陆
        jedisUtil.STRINGS.setEx("USER_SESSION_" + sysUser.getLoginName(), 3600, sessionId);

        LoginRespDTO loginRespDTO = LoginRespDTO.builder()
                .userId(sysUser.getId())
                .sessionId(sessionId)
                .userName(sysUser.getName())
                .build();
        return ResponseVO.success(loginRespDTO);
    }

}
